package com.concurrency.example.commonUnSafe;

import com.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@NotThreadSafe
@Slf4j
public class DateExample1 {
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private final static int clientTotal = 5000;//请求总数
    private final static int maxConcurrency = 200;//同时执行最大线程数

    public static void main(String[] args) throws  Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        final Semaphore semaphore = new Semaphore(maxConcurrency);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(()->{
                try{
                    semaphore.acquire();//如果没达到maxConcurrency可以执行下面的语句，否则阻塞
                    update();
                    semaphore.release();
                    countDownLatch.countDown();
                }catch (Exception e){
                    log.error("exception",e);
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void update(){
       try{
           simpleDateFormat.parse("2018-02-02");
       }catch (Exception e){
           log.error("datePaseExeception",e);
       }
    }
}
